package com.chy.blog_server.modular.map.export;

import com.alibaba.excel.EasyExcel;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述：导出工具类
 * 作者：chenhuiyan
 * 时间：2025/03/22 22:07
 */
public class DynamicExcelUtil {

    /**
     * 导出Excel
     * @param dataList
     * @param response
     */
    public static void exportToExcel(List<Map<String, String>> dataList, String sheetName, HttpServletResponse response,
                                     Map<String, Integer> columnWidthMap) throws IOException {
        // 动态生成表头
        Set<String> headers = dataList.stream()
                .flatMap(map -> map.keySet().stream())
                .collect(Collectors.toSet());

        // 生成表头列表
        List<List<String>> headerList = headers.stream()
                .map(header -> Collections.singletonList(header))
                .collect(Collectors.toList());


        EasyExcel.write(response.getOutputStream())
                .registerWriteHandler(new DynamicColumnWidthHandler(columnWidthMap)) // 关键：列宽处理
                .head(headerList)
                .sheet("高德商家信息")
                .doWrite(dataList.stream()
                        .map(row -> new ArrayList<>(row.values()))
                        .collect(Collectors.toList()));
    }

}
